// api/data_api/statistic.go
package data_api

import (
	"github.com/gin-gonic/gin"
	"github.com/sirupsen/logrus"
	"muziai-server/global"
	"muziai-server/models"
	"muziai-server/utils/res"
	"time"
)

type ChatStatisticResponse struct {
	DateList  []string `json:"dateList"`
	CountList []int    `json:"countList"`
}

func (DataApi) ChatStatisticView(c *gin.Context) {

	now := time.Now()

	startDate := now.AddDate(0, 0, -7).Format("2006-01-02")
	endDate := now.AddDate(0, 0, -1).Format("2006-01-02")

	type Table struct {
		Date  string `gorm:"column:d"`
		Count int    `gorm:"column:c"`
	}

	var dataList []Table
	global.DB.Model(models.ChatModel{}).
		Where("date(created_at) >= ? and date(created_at) <= ?", startDate, endDate).
		Group("date(created_at)").
		Select("date(created_at) as d", " count(id) as c").
		Scan(&dataList)

	var dateCountMap = map[string]int{}
	//fmt.Println(dataList)
	for _, table := range dataList {
		dateObj, err := time.Parse(time.RFC3339, table.Date)
		if err != nil {
			logrus.Warnf("%s 时间解析失败 %s", table.Date, err.Error())
			continue
		}
		date := dateObj.Format("2006-01-02")
		dateCountMap[date] = table.Count
	}
	var data ChatStatisticResponse
	var sT = now.AddDate(0, 0, -7)
	for i := 0; i < 7; i++ {
		date := sT.AddDate(0, 0, i).Format("2006-01-02")
		count := dateCountMap[date]
		data.DateList = append(data.DateList, date)
		data.CountList = append(data.CountList, count)
	}
	res.OkWithData(c, data)
	return
}
